<template>
  <div class="user-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <user-search
        ref="searchFormRef"
        @search="handleSearch"
        @reset="handleReset"
      />

      <!-- 表格区域 -->
      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        empty-text="暂无数据"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="balance" label="账户余额">
          <template #default="scope">
            {{ scope.row.balance ? '￥' + scope.row.balance : '￥0' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >编辑</el-button>

            <el-button
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              link
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '冻结' : '解冻' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          :total="total"
          :page-count="Math.ceil(total / queryParams.pageSize)"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <user-form
        v-model:visible="dialogVisible"
        :user-data="currentUser"
        @success="handleSuccess"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, updateUser, type UserInfo } from '@/api/user'
import UserForm from './components/UserForm.vue'
import UserSearch from './components/UserSearch.vue'

interface User extends UserInfo {}

interface StatusOption {
  value: number
  label: string
}

const loading = ref(false)
const userList = ref<User[]>([])
const total = ref(0)

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  username: '',
  phone: '',
  status: undefined as number | undefined
})

// 添加组件状态
const dialogVisible = ref(false)
const currentUser = ref<User>()

// 状态选项
const statusOptions: StatusOption[] = [
  { value: 1, label: '正常' },
  { value: 0, label: '冻结' }
]

// 获取用户列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getUserList(queryParams.value)
    const { list, total: totalStr } = res.data

    if (!Array.isArray(list)) {
      throw new Error('list 不是数组')
    }

    userList.value = list
    total.value = parseInt(totalStr) || 0
  } catch (error) {
    console.error('获取用户列表失败：', error)
    userList.value = []
    total.value = 0
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = (params: any) => {
  queryParams.value = {
    ...queryParams.value,
    ...params,
    pageNum: 1
  }
  getList()
}

// 重置
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    username: '',
    phone: '',
    status: undefined
  }
  getList()
}

// 分页
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val
  getList()
}

const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val
  getList()
}

// 新增用户
const handleAdd = () => {
  currentUser.value = undefined
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row: User) => {
  currentUser.value = row
  dialogVisible.value = true
}


// 状态变更
const handleStatusChange = async (row: User) => {
  const statusText = row.status === 1 ? '冻结' : '解冻'
  const newStatus = row.status === 1 ? 0 : 1

  try {
    await ElMessageBox.confirm(
      `确认要${statusText}用户"${row.username}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await updateUser(Number(row.id), {
      username: row.username,
      phone: row.phone || undefined,
      status: newStatus
    })
    ElMessage.success(`${statusText}成功`)
    getList()
  } catch (error) {
    console.error(`${statusText}失败：`, error)
    ElMessage.error(`${statusText}失败`)
  }
}

// 添加表单提交成功回调
const handleSuccess = () => {
  getList()
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  })
}

// 获取状态标签
const getStatusLabel = (status: number) => {
  return statusOptions.find(item => item.value === status)?.label || '-'
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
  height: calc(100vh - 120px);
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: auto;
  padding: 20px 0;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
}
</style>
